package com.chinackts.common.log.service;

import com.chinackts.common.log.model.Log;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@RequiredArgsConstructor
@Slf4j
public class LogService {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    private String lastCheckedMonth = null;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMM");


    private synchronized void ensureTable(Date time) {
        String suffix = DATE_FORMAT.format(time);
        if (suffix.equals(lastCheckedMonth)) {
            return;
        }
        log.info("************************ 新建日志表 ************************");

        String tableName = "log_" + suffix;
        String sql = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
                "  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键'," +
                "  `s_id` varchar(20) NOT NULL COMMENT '会话ID'," +
                "  `org_code` varchar(10) NOT NULL COMMENT '组织机构代码'," +
                "  `type` varchar(10) NOT NULL COMMENT '采集类型'," +
                "  `success` varchar(1) NOT NULL COMMENT '是否采集成功：0-失败 1-成功'," +
                "  `request_url` varchar(100) NOT NULL COMMENT '请求路径'," +
                "  `request_msg` text NOT NULL COMMENT '请求报文'," +
                "  `response_msg` longtext NULL COMMENT '响应报文'," +
                "  `time` int NULL COMMENT '耗时'," +
                "  `create_time` datetime NOT NULL COMMENT '创建时间'," +
                "  PRIMARY KEY (`id`)," +
                "  INDEX `ORG_CODE_IDX`(`org_code`) USING BTREE," +
                "  INDEX `TYPE_IDX`(`type`) USING BTREE," +
                "  INDEX `SUCCESS_IDX`(`success`) USING BTREE" +
                ")";
        namedParameterJdbcTemplate.getJdbcTemplate().execute(sql);
        lastCheckedMonth = suffix;
    }

    @Async("logExecutor")
    public void log(Log log) {
        Date now = new Date();
        ensureTable(now);
        String sql = "INSERT INTO log (s_id, org_code, type, success, request_url, request_msg, response_msg, time, create_time) " +
                "VALUES (:s_id, :org_code, :type, :success, :request_url, :request_msg, :response_msg, :time, :create_time)";
        this.namedParameterJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(log));
    }
}
